<template>
  <div>
    <!-- 顶部导航栏 -->
    <div class="naviBar">
      <van-sticky>
        <van-nav-bar
          title="订单确认"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft()"
        />
      </van-sticky>
    </div>
    <!-- 中间数据卡片 -->
    <div class="orderCar">
      <!-- 服务地址 -->
      <div class="serviceAddress" @click="showAddressPopup()">
        <van-cell icon="location-o">
          <!-- 使用 title 插槽来自定义标题 -->
          <template #title>
            <span class="custom-title">服务地址</span>
          </template>
          <template #label>
            <van-row type="flex">
              <van-col span="12" class="custom-label"
                >姓名：{{ addressObj.name }}</van-col
              >
              <van-col span="12" class="custom-label"
                >电话：{{ addressObj.tel }}</van-col
              >
            </van-row>
            <van-row type="flex">
              <van-col span="24" class="custom-label"
                >地址：{{ addressObj.address }}</van-col
              >
            </van-row>
          </template>
        </van-cell>
      </div>

      <!-- 订单详情 -->
      <div class="orderDetail">
        <van-cell-group>
          <van-cell icon="orders-o">
            <!-- 使用 title 插槽来自定义标题 -->
            <template #title>
              <span class="custom-title">订单详情</span>
            </template>
            <template #label>
              <van-row
                type="flex"
                v-for="order in orderArray"
                :key="order.number"
              >
                <!-- 产品名称 -->
                <van-col span="8" class="custom-label">{{
                  order.productName
                }}</van-col>
                <!-- 产品价格 -->
                <van-col span="8" class="custom-label">{{
                  "￥" + order.price
                }}</van-col>
                <!-- 产品数量 -->
                <van-col span="8" class="custom-label">{{
                  "x" + order.number
                }}</van-col>
              </van-row>
            </template>
          </van-cell>
          <van-cell style="padding: 7px 0px">
            <!-- 使用 title 插槽来自定义标题 -->
            <template #title> </template>
            <template #label>
              <van-row type="flex">
                <van-col span="8" class="custom-label"></van-col>
                <van-col span="8" class="custom-label"></van-col>
                <!-- 总计 -->
                <van-col span="8" class="custom-label"
                  >总计：{{ total }}</van-col
                >
              </van-row>
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 服务时间 -->
      <div class="serviceTime" @click="showTimePopup()">
        <van-cell title="服务时间" icon="clock-o" :value="orderDate" />
      </div>
    </div>
    <!-- 提交按钮 -->
    <div class="submitButton" @click="postOrder()">
      <van-button type="primary" size="large">提交订单</van-button>
    </div>
    <!-- 地址弹出框 -->
    <van-popup
      v-model="popupShowAddress"
      round
      position="bottom"
      :style="{ height: '70%' }"
      close-icon="close"
      closeable
    >
      <div class="addrPopTitle">选择地址</div>
      <div>
        <van-address-list
          v-model="chosenAddressId"
          :list="addressList"
          default-tag-text="默认"
          @add="addrSubmit()"
        />
      </div>
    </van-popup>

    <!-- 时间弹出框 -->
    <van-popup
      v-model="popupShowTime"
      round
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="confirmTime()"
        @cancel="cancelTime()"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations, mapGetters } from "vuex";
import moment from "moment";
import { get, post, post_json } from "@/http/axios";

export default {
  data() {
    return {
      // 控制地址时间框的显隐
      popupShowAddress: false,

      // 控制时间弹出框显隐
      popupShowTime: false,

      // 选中的地址对象
      addressObj: {},

      // 地址数据
      chosenAddressId: 1,
      addressList: [],

      // 选择年月日小时时间控件
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),

      // 选中的时间格式化
      orderDate: "",

      // 选中的时间时间戳
      timestamp: "",
    };
  },
  computed: {
    // 获得总价格
    ...mapGetters("shopcart", ["total"]),

    // 从vuex中获得购物车已选择数据
    ...mapState("shopcart", ["orderLines"]),

    // ...从vuex中获得用户数据
    ...mapState("user", ["userInfo"]),

    // 商品数组，剔除数量为 0
    orderArray() {
      const orderArray = Array.from(this.orderLines.values());
      return orderArray.filter((orderArray) => orderArray.number !== 0);
    },
  },
  methods: {
    // 请求用户信息方法
    ...mapActions("user", ["getUserInfo"]),

    // 引入shopcar vuex中的 addShopcart方法
    ...mapMutations("shopcart", ["addShopcart", "clearShopcart"]),

    // 提交订单
    async postOrder() {
      const data = {
        addressId: this.addressObj.addressId,
        customerId: this.userInfo.id,
        orderLines: this.orderArray,
        serviceTime: this.timestamp,
      };
      if (data.orderLines.length !== 0) {
        // 发送提交请求
        const res = await post_json("/order/submitOrder", data);

        // 如果订单提交成功，清空购物车并提示
        if (res.status === 200) {
          this.clearShopcart();
          this.$toast("订单提交成功");
          this.$router.push({
            path: "/manager/order?navPage=1",
          });
        } else {
          this.$toast(res.data.message);
        }
      } else {
        this.$toast("商品不能为空");
      }
    },

    // 请求获得用户地址
    async getUserAddress() {
      const data = {
        page: 1,
        pageSize: 20,
        userId: this.userInfo.id,
      };
      const res = await get("/address/pageQuery", data);
      const addrs = res.data.data.list;

      // 将请求到的用户地址格式化后赋值给组件数组
      for (const index in addrs) {
        this.addressList.push({
          id: index + 1,
          addressId: addrs[index].id,
          name: addrs[index].username,
          tel: addrs[index].telephone,
          address: addrs[index].address,
          isDefault: addrs[index].isDefault === 1 ? true : false,
        });
      }

      // 遍历格式化后的地址组件地址数据，将默认地址赋值给选中地址的数组，
      // 将默认被选中项赋值给组件绑定的值
      this.addressList.forEach((address) => {
        if (address.isDefault) {
          this.addressObj = address;
          this.chosenAddressId = address.id;
        }
      });
    },

    // 提交选中地址
    addrSubmit() {
      this.popupShowAddress = false;
      this.addressList.forEach((address) => {
        if (address.id === this.chosenAddressId) {
          this.addressObj = address;
        }
      });
    },

    // 时间取消
    cancelTime() {
      this.popupShowTime = false;
    },

    // 确认时间
    confirmTime() {
      this.popupShowTime = false;
      this.orderDate = moment(this.currentDate).format("YYYY-MM-DD hh:mm:ss");
      this.timestamp = this.currentDate.getTime();
    },

    // 格式化时间菜单
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }

      return val;
    },

    // 调用让地址弹出框弹出
    showAddressPopup() {
      this.popupShowAddress = true;
    },

    // 调用让时间弹出框弹出
    showTimePopup() {
      this.popupShowTime = true;
    },

    // 导航栏返回
    onClickLeft() {
      this.$router.go(-1);
    },
  },
  created() {
    // 获得用户数据
    this.getUserInfo().then(() => {
      // 请求获得地址数据
      this.getUserAddress();

      // 提交默认地址
      this.addrSubmit();
    });

    // 显示时间
    this.confirmTime();
  },
};
</script>

<style>
body
{
  background: #f7f8fa;
}
.van-button--primary
{
  background: linear-gradient(to right, #ff6034, #ee0a24);
  border:none
}
#app>div
{
  height: 100%;
}
.submitButton
{
  position: relative;
  bottom: unset;
}
.orderCar > div {
  width: 96%;
  margin: 10px auto;
}
.van-cell{
  background: white;
  border-radius: 8px;
}

.addrPopTitle {
  width: 100%;
  height: 50px;
  text-align: center;
  line-height: 50px;
}
</style>

